#include"comm.hpp"


int main()
{
    // 获取key值
    key_t key = ftok(PATH, PROJ_ID);
    Log("client create key success", Debug);
    cout << "client key ::" << deToHex(key) << endl; 

    // client无需再创建shm，直接获取shmid即可
    int shmid = shmget(key, SIZE, IPC_CREAT | 0666);
    if(shmid == -1)
    {
        Log("client get key fail", Error);
        exit(1);
    }
    Log("client get key success", Debug);
    cout << "client shmid::" << shmid << endl;
    //sleep(5);

    // client端与创建出的shm建立映射
    char* shmaddr = (char*)shmat(shmid, nullptr, 0);
    if(shmaddr == (char*)-1)
    {
        Log("client attach fail", Error);
        exit(2);
    }
    Log("client attach success", Debug);
    //sleep(20);

    // // ipc
    // for(char c = 'a'; c < 'f'; ++c)
    // {
    //     //snprintf(shmaddr, SIZE, "hello server, I'm client, my pid::%d, send char::%c", getpid(), c);
    //     shmaddr[c - 'a'] = c;
    //     sleep(1);
    // }
    // // 写入完毕，输入quit让server端结束读取
    // strcpy(shmaddr, "quit");
    
    // // ipc
    // while(true)
    // {
    //     write(1, "client #", 8);
    //     ssize_t ret = read(0, shmaddr, SIZE - 1);
    //     if(ret > 0)
    //     {
    //         shmaddr[ret - 1] = 0;
    //         if(strcmp(shmaddr, "quit") == 0) break;
    //     }
    // }

    // client 通信前写打开文件
    int fd = OpenFifo(FIFO_PATH, WRITE);

    // ipc
    while(true)
    {
        // 先进行写入
        write(1, "client #> ", 10);
        int ret = read(0, shmaddr, SIZE - 1);
        if(ret > 0)
        {
            shmaddr[ret - 1] = 0;
        }
        // 写入完毕再让server端读取，发送信号
        SendSignal(fd);
        // 接收到quit时就退出
        if(strcmp(shmaddr, "quit") == 0)
        {
            Log("client quit", Debug);
            break;
        }
    }
    // 退出后关闭文件
    CloseFifo(fd);


    // client端与shm去掉映射，不必删除映射
    if(shmdt(shmaddr) == -1)
    {
        Log("client detach fail", Error);
        exit(3);
    }
    //sleep(5);
    Log("client detach success", Debug);

    Log("client quit", Debug);    
    return 0;
}